﻿using Qlab.SharedKernel.Exceptions;
using Qlab.SharedKernel.Extensions;
using Qlab.SharedKernel.Interfaces;
using Qlab.SharedKernel.JsonWebToken;
using Newtonsoft.Json;
using System;
using System.Text;

namespace Qlab.Infrastructure
{
    public class JsonWebToken : IJsonWebToken
    {
        public string CreateToken(ApplicationUser user)
        {
            string appId = ConfigExtension.Configuration.GetSection("JsonWebToken:AppId").Value;
            string secretKey = ConfigExtension.Configuration.GetSection("JsonWebToken:SecretKey").Value;

            string userString = JsonConvert.SerializeObject(user);

            string token = userString + "|" + EncryptExtension.MD5Encrypt(appId + secretKey + userString);

            return Convert.ToBase64String(Encoding.UTF8.GetBytes(token));
        }

        public ApplicationUser GetUserByToken(string token)
        {
            if (string.IsNullOrEmpty(token))
                throw new UnAuthorizedException("对不起，您未登录，请先登录！");

            if (!token.Contains("|"))
                throw new UnAuthorizedException("非法登录！");

            string tokenString = Encoding.UTF8.GetString(Convert.FromBase64String(token));

            string userString = tokenString.Split('|')[0];

            var user = JsonConvert.DeserializeObject<ApplicationUser>(userString);

            if (user == null)
                throw new UnAuthorizedException("非法登录！");

            return user;
        }

        public void ValidateToken(string token)
        {
            var user = GetUserByToken(token);

            int expired = int.Parse(ConfigExtension.Configuration.GetSection("JsonWebToken:Expired").Value);

            //校验过期时间
            var minutes = (DateTime.Now - user.LoginTime).TotalMinutes;
            if (minutes > expired)
                throw new UnAuthorizedException("对不起，登录超时，请重新登录！");

            // 校验秘钥
            if (CreateToken(user) != token)
                throw new UnAuthorizedException("非法登录！");
        }
    }
}